<template>
  <j-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :fullscreen.sync="fullscreen"
    @cancel="handleCancel"
    :footer="null"
  >
    <a-spin :spinning="confirmLoading">
      <a-card :bordered="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules">
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="actCd" label="活动编码">
          <span v-if="!model.id">自动生成</span>
          <span v-else>{{ model.actCd }}</span>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="actNm" label="活动名称">
          <a-input placeholder="" v-model.trim="model.actNm" :disabled="!isEdit" style="width: 350px" />
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="dateRange" label="活动时间">
          <a-range-picker
            :show-time="{ defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')] }"
            format="YYYY-MM-DD HH:mm:ss"
            v-model="model.dateRange"
            @change="handleDateChange1"
            :disabled="!isEdit"
          />
        </a-form-model-item>
        <!--部门分配-->
        <a-form-model-item label="适用门店" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="selecteddeparts">
          <a-cascader
                :options="departModel.departTreeOptions"
                @change="onDepartChange"
                :showSearch="true"
                expand-trigger="hover"
                placeholder=""
                :fieldNames="departModel.fieldNames"
                style="width: 300px"
                v-model="model.selecteddeparts"
                :disabled="!isEdit"
              />
        </a-form-model-item>
        <a-form-model-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          prop="ruleType"
          label="优惠方式"
          v-show="false"
        >
          <a-radio-group name="ruleType" :default-value="11" v-model="model.ruleType">
            <a-radio :value="11"> 按商品 </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="actType" label="优惠模式">
          <a-radio-group
            name="actType"
            default-value="20"
            v-model="model.actType"
            :disabled="model.id ? true: false"
            @change="handleActType"
          >
            <a-radio :value="20"> 折扣 </a-radio>
            <a-radio :value="22"> 特价 </a-radio>
            <a-radio :value="21"> 立减 </a-radio>
          </a-radio-group>
          <div style="color:#777">优惠模式设置后不能修改</div>
        </a-form-model-item>
        <a-form-model-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          prop="digit"
          label="结算金额小数位"
          v-if="isDiscount"
        >
          <a-radio-group name="digit" default-value="1" v-model="model.digit" :disabled="!isEdit">
            <a-radio :value="1"> 抹零 </a-radio>
            <a-radio :value="2"> 四舍五入 </a-radio>
            <a-radio :value="3"> 向上取整 </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="useDesc" label="使用规则说明">
          <a-textarea placeholder="" v-model.trim="model.useDesc" :disabled="!isEdit" style="width: 350px" />
        </a-form-model-item>

        <a-divider></a-divider>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="memberScope" label="限制参加用户">
          <a-radio-group name="memberScope" default-value="A" v-model="model.memberScope" :disabled="!isEdit">
            <a-radio value="A"> 不限制 </a-radio>
            <a-radio value="M"> 仅限会员参加 </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="useLimitRule" label="共享活动限制">
          <span style="display: inline-block; padding: 0 5px">不参与</span>
          <span class="limitCheck">
            <a-checkbox-group name="useLimitRule" v-model="model.useLimitRule" :disabled="!isEdit">
              <a-checkbox value="not_give_points">赠送积分</a-checkbox>
              <a-checkbox value="not_use_points">抵扣积分</a-checkbox>
              <a-checkbox value="not_use_coupon">使用优惠券</a-checkbox>
            </a-checkbox-group>
          </span>
        </a-form-model-item>

        <a-form-model-item :wrapperCol="{ span: 5, offset: 5 }">
          <a-col :md="24" :sm="24">
            <a-form-model-item :wrapperCol="{ span: 5, offset: 5 }">
              <a-button type="primary" htmlType="submit" @click="handleOk" v-if="isEdit">保存活动</a-button>
              <a-button
                type="primary"
                htmlType="submit"
                @click="
                  () => {
                    this.isEdit = true
                  }
                "
                v-else
                >编辑活动</a-button
              >
            </a-form-model-item>
          </a-col>
        </a-form-model-item>
      </a-form-model>
      <a-tabs defaultActiveKey="1" style="margin-top: -15px">
        <a-tab-pane tab="可用商品设置" key="1">
          <div class="table-operator">
            <a-button type="default" @click="newRow" :disabled="actId === '0'">添加商品</a-button>
            <a-button type="default" @click="batchRow" :disabled="actId === '0'">批量设置</a-button>
            <a-button type="default" @click="autoRule" :disabled="actId === '0'">自动添加商品规则</a-button>
            <a-button type="default" @click="clearProd" :disabled="actId === '0'">清空所有商品</a-button>
            <a-divider type="vertical" />
            <a-button type="default" @click="importProd" :disabled="actId === '0'">导入商品</a-button>
            <a-button type="default" @click="exportProd('单品促销')" :disabled="actId === '0'">导出商品</a-button>
          </div>
          <div class="ant-alert ant-alert-info" style="margin-bottom: 16px" v-if="selectedRowKeys.length > 0">
            <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
            <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
            >项
            <a style="margin-left: 24px" @click="onClearSelected">清空</a>
          </div>
          <a-table
            :columns="columns"
            :dataSource="dataSource"
            size="middle"
            bordered
            rowKey="id"
            :pagination="ipagination"
            :loading="loading"
            class="j-table-force-nowrap"
            @change="handleTableChange"
          >
            <template v-for="col in ['special', 'discount', 'reduce']" :slot="col" slot-scope="text, record">
              <div class="editable-cell" :key="col">
                <div v-if="editable['key_' + record.id]">
                  <a-input-number
                    :min="minLimit"
                    :max="maxLimit"
                    style="width: 200px"
                    :defaultValue="text"
                    @change="(number) => editCellHandleChange(number, record.id, record.markPrice, col)"
                    @pressEnter="editCellCheck(record.id)"
                  /><a-icon type="check" @click="editCellCheck(record.id)" class="editable-cell-icon-check" />
                  <a-icon type="close" @click="handleEditCell(record.id, false)" class="editable-cell-icon" />
                </div>
                <div v-else>
                  {{ text || ' ' }}
                  <a-icon type="edit" @click="handleEditCell(record.id, true)" class="editable-cell-icon" />
                </div>
              </div>
            </template>
            <template slot="operation" slot-scope="text, record">
              <a-popconfirm title="是否要删除此行？" @confirm="removeRow(record.id)"><a>删除</a></a-popconfirm>
            </template>
            <div slot="itemCodeFilterDropdown" style="padding: 8px">
              <a-input
                v-ant-ref="(c) => (searchInput = c)"
                v-model="queryParam.params.itemCode"
                style="width: 188px; margin-bottom: 8px; display: block"
              />
              <a-button size="small" style="width: 90px" @click="handleSearch()"> 查询 </a-button>
            </div>
            <a-icon slot="filterIcon" type="search" :style="{ color: '#108ee9' }" />
            <div slot="markPriceFilterDropdown" style="padding: 8px">
              <a-input-number
                v-ant-ref="(c) => (searchInputPrice = c)"
                v-model="queryParam.params.markPrice"
                :min="0"
                :max="999999"
                style="width: 188px; margin-bottom: 8px; display: block"
              />
              <a-button size="small" style="width: 90px" @click="handleSearch()"> 查询 </a-button>
            </div>
          </a-table>
        </a-tab-pane>
      </a-tabs>
      <!-- 表单区域 -->
      <SelectProductSpuList ref="selectSpuForm" @ok="selectOk"></SelectProductSpuList>
      <a-modal v-model="batchVisible" title="批量设置" @ok="handleBatchOk" :maskClosable="false">
        <a-spin :spinning="batchConfirmLoading">
          <a-form-model ref="batchForm" :model="batchModel" :rules="validatorRules1">
            <a-form-model-item
              :labelCol="{
                xs: { span: 24 },
                sm: { span: 8 },
              }"
              :wrapperCol="wrapperCol"
              prop="batchValue"
              :label="batchLabel"
            >
              <a-input-number
                :min="minLimit"
                :max="maxLimit"
                v-model="batchModel.batchValue"
                style="width: 200px"
              ></a-input-number>
            </a-form-model-item>
            <a-form-model-item
              :labelCol="{
                xs: { span: 24 },
                sm: { span: 8 },
              }"
              :wrapperCol="wrapperCol"
              label="提示"
              v-if="batchLabel == '特价'"
            >
              <span>可填写不超过销售价的整数</span>
            </a-form-model-item>
          </a-form-model>
        </a-spin>
      </a-modal>

      <SignProImport ref="SignProImport" ok="handleImp"></SignProImport>

      <a-modal v-model="autoVisible" title="设置自动添加商品规则" @ok="handleAutoOk" :maskClosable="false" :width="800">
        <a-spin :spinning="autoConfirmLoading">
          <a-form-model ref="autoForm" :model="autoModel" :rules="validatorRules2">
            <a-form-model-item
              :labelCol="{
                xs: { span: 24 },
                sm: { span: 8 },
              }"
              :wrapperCol="wrapperCol"
              prop="priceType"
              label="类型"
              v-if="autoModel.ruleType === 1"
            >
              <a-radio-group v-model="autoModel.priceType" @change="handlePriceType">
                <a-radio value="tail">尾数</a-radio>
                <a-radio value="price">零售价</a-radio>
              </a-radio-group>
            </a-form-model-item>
            <a-form-model-item
              :labelCol="{
                xs: { span: 24 },
                sm: { span: 8 },
              }"
              :wrapperCol="wrapperCol"
              prop="priceTail"
              label="价格尾数"
              v-if="autoModel.ruleType === 1 && autoModel.priceType == 'tail'"
            >
              <a-select v-model="autoModel.priceTail" allowClear style="width: 200px">
                <a-select-option v-for="(item, index) in priceTail" :key="index" :value="item.value">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item
              :labelCol="{
                xs: { span: 24 },
                sm: { span: 8 },
              }"
              :wrapperCol="wrapperCol"
              prop="priceRange"
              label="价格范围"
              v-if="autoModel.ruleType === 1 && autoModel.priceType == 'tail'"
            >
              <a-input-group compact>
                <a-input-number
                  style="width: 130px; text-align: center"
                  placeholder="最小值(包含)"
                  :min="0"
                  :max="999999"
                  :formatter="limitNumber"
                  :parser="limitNumber"
                  v-model="autoModel.priceTailBegin"
                  allowClear
                />
                <a-input
                  style="width: 30px; border-left: 0; pointer-events: none; backgroundcolor: #fff"
                  placeholder="~"
                  disabled
                />
                <a-input-number
                  style="width: 130px; text-align: center; border-left: 0"
                  placeholder="最大值(包含)"
                  :min="0"
                  :max="999999"
                  :formatter="limitNumber"
                  :parser="limitNumber"
                  v-model="autoModel.priceTailEnd"
                  allowClear
                />
              </a-input-group>
            </a-form-model-item>
            <a-form-model-item
              :labelCol="{
                xs: { span: 24 },
                sm: { span: 8 },
              }"
              :wrapperCol="wrapperCol"
              prop="priceTail"
              label="零售价格"
              v-if="autoModel.ruleType === 2 || (autoModel.ruleType === 1 && autoModel.priceType == 'price')"
            >
              <a-input-number
                :min="1"
                :max="999999"
                v-model="autoModel.priceTail"
                style="width: 200px"
              ></a-input-number>
            </a-form-model-item>
            <a-form-model-item
              :labelCol="{
                xs: { span: 24 },
                sm: { span: 8 },
              }"
              :wrapperCol="wrapperCol"
              prop="autoValue"
              :label="autoLabel"
            >
              <a-input-number
                :min="minLimit"
                :max="maxLimit"
                v-model="autoModel.autoValue"
                style="width: 200px"
              ></a-input-number>
            </a-form-model-item>
            <a-form-model-item
              :labelCol="{
                xs: { span: 24 },
                sm: { span: 8 },
              }"
              :wrapperCol="wrapperCol"
              prop="bizStatus"
              label="是否启用"
            >
              <a-select v-model="autoModel.bizStatus" allowClear style="width: 200px">
                <a-select-option v-for="(item, index) in yesNoState" :key="index" :value="item.value">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-form-model>
        </a-spin>
      </a-modal>
      </a-card>
    </a-spin>
  </j-modal>
</template>

<script>
import { postAction, deleteAction, downFile } from '@/api/manage'
import { queryDepartTreeList1 } from '@/api/api'
import { filterObj } from '@/utils/util'
import SelectProductSpuList from './SelectProductSpuList'
import moment from 'moment'
import SignProImport from './SignProImport'
import { getAction } from '@/api/manage'
import { Modal } from 'ant-design-vue'
import { limitNumber, isUnSignInt, isUnSignDig2 } from '@/utils/util'

export default {
  name: 'posMarketActModalSignProDis',
  components: {
    SelectProductSpuList,
    SignProImport,
  },
  data() {
    return {
      moment,
      limitNumber,
      isUnSignInt,
      isUnSignDig2,
      title: '操作',
      searchInput: null,
      searchInputPrice: null,
      /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
      queryParam: {
        params: {},
      },
      /* 数据源 */
      dataSource: [],
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      /* 排序参数 */
      isorter: {
        column: 'createTime',
        order: 'desc',
      },
      /* 筛选参数 */
      filters: {},
      /* table加载状态 */
      loading: false,
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
      /* 查询折叠 */
      toggleSearchStatus: false,
      /* 高级查询条件生效状态 */
      superQueryFlag: false,
      /* 高级查询条件 */
      superQueryParams: '',
      /** 高级查询拼接方式 */
      superQueryMatchType: 'and',
      fullscreen: true,
      visible: false,
      batchVisible: false,
      importVisible: false,
      batchConfirmLoading: false,
      autoConfirmLoading: false,
      isEdit: true,
      model: {},
      batchModel: {},
      batchLabel: '',
      autoLabel: '',
      autoValue: '',
      autoModel: {
        ruleType: 1,
      },
      isDiscount: false,
      autoVisible: false,
      minLimit:1,
      maxLimit: 99999,
      //departTreeOptions: [],
      departModel: {
        departTreeOptions: [],
        fieldNames: { label: 'title', value: 'value', children: 'children' },
      },
      orgIds: '',
      actId: '0',
      shopIds: '',
      orgType: 2,
      scopeShops: [],
      userScope: 'ALL',
      editable: {},
      cellData: [],
      priceTail: [
        { text: '0', value: '0' },
        { text: '1', value: '1' },
        { text: '2', value: '2' },
        { text: '3', value: '3' },
        { text: '4', value: '4' },
        { text: '5', value: '5' },
        { text: '6', value: '6' },
        { text: '7', value: '7' },
        { text: '8', value: '8' },
        { text: '9', value: '9' },
      ],
      yesNoState: [
        { text: '是', value: '1' },
        { text: '否', value: '0' },
      ],
      setColumn: '',
      itemListData: [],
      fieldNames: { label: 'title', value: 'value', children: 'children' },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      // table
      cloneColumns: [],
      searchText: '',
      searchedColumn: '',
      columns: [
        {
          title: '商品名称',
          dataIndex: 'itemName',
          width: 400,
        },
        {
          title: '商品编码',
          dataIndex: 'itemCode',
          scopedSlots: {
            filterDropdown: 'itemCodeFilterDropdown',
            filterIcon: 'filterIcon',
          },
          onFilterDropdownVisibleChange: (visible) => {
            if (visible) {
              setTimeout(() => {
                this.searchInput.focus()
              }, 0)
            }
          },
        },
        {
          title: '季节',
          dataIndex: 'itemSession',
        },
        {
          title: '类型',
          dataIndex: 'itemType',
        },
        {
          title: '零售价',
          dataIndex: 'markPrice',
          scopedSlots: {
            filterDropdown: 'markPriceFilterDropdown',
            filterIcon: 'filterIcon',
          },
          onFilterDropdownVisibleChange: (visible) => {
            if (visible) {
              setTimeout(() => {
                this.searchInputPrice.focus()
              }, 0)
            }
          },
        },
        {
          title: '折扣',
          dataIndex: 'discount',
          width: '20%',
          scopedSlots: { customRender: 'discount' },
        },
        {
          title: '特价',
          dataIndex: 'special',
          width: '20%',
          scopedSlots: { customRender: 'special' },
        },
        {
          title: '立减',
          dataIndex: 'reduce',
          width: '20%',
          scopedSlots: { customRender: 'reduce' },
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      confirmLoading: false,
      validatorRules: {
        actNm: [{ required: true, message: '必填项' }],
        actType: [{ required: true, message: '必填项' }],
        dateRange: [{ required: true, message: '必填项' }],
        selecteddeparts: [{ required: true, message: '必填项' }],
        digit: [{ required: true, message: '必填项' }],
      },
      validatorRules1: {
        batchValue: [{ required: true, message: '必填项' }],
      },
      validatorRules2: {
        autoValue: [{ required: true, message: '必填项' }],
        priceTail: [{ required: true, message: '必填项' }],
        bizStatus: [{ required: true, message: '必填项' }],
        priceType: [{ required: true, message: '必填项' }],
      },
      url: {
        add: '/marketing/posMarketAct/add',
        edit: '/marketing/posMarketAct/edit',
        listItemUrl: '/marketing/posGoodsSaleRule/listGoodsRuleItem',
        delItemUrl: '/marketing/posGoodsSaleRule/delete',
        saveItemUrl: '/marketing/posGoodsSaleRule/batchSaveItem',
        saveItemUrl2: '/marketing/posGoodsSaleRule/batchSaveItem2',
        exportProdXlsUrl: '/marketing/posGoodsSaleRule/exportXls',
        posMarketActAuto: '/marketing/posMarketActAuto/addOrEdit',
        queryByActId: '/marketing/posMarketActAuto/queryByActId',
        deleteAllItemUrl: '/marketing/posGoodsSaleRule/deleteAll',
      },
    }
  },
  created() {
    console.log('created')
  },
  methods: {
    handlePriceType() {
      this.$set(this.autoModel, 'priceTail', null)
    },
    handleSearch(e) {
      this.loadData(1)
    },
    handleImp() {
      this.importVisible = false
      this.loadData()
    },
    importProd() {
      this.importVisible = true
      this.$refs.SignProImport.init(this.actId, this.model.scopeShopIds)
    },
    exportProd(fileName) {
      if (!fileName || typeof fileName != 'string') {
        fileName = '导出文件'
      }
      let param = { actId: this.actId, actType: this.model.actType }
      downFile(this.url.exportProdXlsUrl, param).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    handleEditCell(id, isEdit) {
      this.$set(this.editable, 'key_' + id, isEdit)
    },
    editCellHandleChange(value, id, markPrice, col) {
      console.log('value=', value, ',id=', id, 'col=', col)

      let newCellData = [...this.cellData]
      let target = newCellData.filter((item) => id === item.id)[0]
      if (target) {
        target['reduce'] = null, target['discount'] = null, target['special'] = null, 
        target[col] = value
        target['markPrice'] = markPrice
        this.cellData = newCellData
      } else {
        target = {}
        target['id'] = id
        target['markPrice'] = markPrice
        target[col] = value
        newCellData.push(target)
        this.cellData = newCellData
      }
    },
    checkCellValue(cellData) {
      console.log(cellData)
      let reduce = cellData[0].reduce
      let discount = cellData[0].discount
      let special = cellData[0].special
      if(reduce){
        let res = this.isUnSignInt(reduce)
        if(!res){
          this.$message.warning('只能输入整数')
          return res
        }
      }
      if(discount){
        let res = this.isUnSignDig2(discount)
        if(!res){
          this.$message.warning('最多1位小数')
          return res
        }
      }
      if(special){
        let res = this.isUnSignInt(special)
        if(!res){
          this.$message.warning('只能输入整数')
          return res
        }
      }
      return true
    },
    editCellCheck(id) {
      console.log('id=', id)
      if (this.cellData.length === 0) {
        return
      }

      if (!this.checkCellValue(this.cellData)) {
        return false
      }

      let that = this
      this.editable['key_' + id] = false
      let param = this.cellData
      console.log('param=', param)

      postAction(this.url.saveItemUrl, param)
        .then((res) => {
          if (res.success) {
            this.actId = res.result
            that.isEdit = false
            that.$message.success(res.message)
            that.loadData()
          } else {
            that.$message.warning(res.message)
          }
        })
        .finally(() => {
          that.batchConfirmLoading = false
          that.batchClose()
        })
    },
    onCellChange(key, dataIndex, value) {
      const dataSource = [...this.dataSource]
      const target = dataSource.find((item) => item.key === key)
      if (target) {
        target[dataIndex] = value
        this.dataSource = dataSource
      }
    },
    handleActType() {
      if (this.cloneColumns.length === 0) {
        this.cloneColumns = Object.assign(this.columns)
      }

      if (this.model.actType === 20) {
        this.isDiscount = true
        this.autoModel.ruleType = 1
        this.batchLabel = '折扣(1-10之间)'
        this.minLimit = 1
        this.maxLimit = 10
        this.setColumn = 'discount'
        const newColumns = this.cloneColumns.filter(
          (item) => item.dataIndex !== 'special' && item.dataIndex !== 'reduce'
        )
        this.columns = newColumns
      } else if (this.model.actType === 22) {
        this.isDiscount = false
        this.autoModel.ruleType = 2
        this.model.digit = 0
        this.batchLabel = '特价'
        this.minLimit = 1
        this.maxLimit = 99999
        this.setColumn = 'special'
        const newColumns = this.cloneColumns.filter(
          (item) => item.dataIndex !== 'discount' && item.dataIndex !== 'reduce'
        )
        this.columns = newColumns
      } else if (this.model.actType === 21) {
        this.isDiscount = false
        this.autoModel.ruleType = 1
        this.model.digit = 0
        this.batchLabel = '立减'
        this.minLimit = 0
        this.maxLimit = 99999
        this.setColumn = 'reduce'
        const newColumns = this.cloneColumns.filter(
          (item) => item.dataIndex !== 'special' && item.dataIndex !== 'discount'
        )
        this.columns = newColumns
      }
      console.log('autoModel', this.autoModel)
    },
    saveDetail() {},
    buildBatchParam() {
      for (let item of this.selectionRows) {
        this.handlerRowChange(item.id, item.markPrice, this.batchModel.batchValue, this.setColumn)
      }
      console.log('itemListData=', this.itemListData)
      return this.itemListData
    },
    batchClose() {
      this.batchVisible = false
      this.batchModel = {}
      this.onClearSelected()
      this.itemListData = []
    },
    autoClose() {
      this.autoVisible = false
      this.autoModel = {}
    },
    handleBatchOk() {
      const that = this
      // 触发表单验证
      this.$refs.batchForm.validate((valid) => {
        if (valid) {
          that.batchConfirmLoading = true

          // let param = that.buildBatchParam()
          let param = {
            actId: this.model.id,
          }
          param[this.setColumn] = this.batchModel.batchValue
          postAction(this.url.saveItemUrl2, param)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData()
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.batchConfirmLoading = false
              that.batchClose()
            })
        } else {
          return false
        }
      })
    },

    handleAutoOk() {
      const that = this
      // 触发表单验证
      this.$refs.autoForm.validate((valid) => {
        if (valid) {
          that.autoConfirmLoading = true

          let param = that.autoModel
          param['actId'] = that.model.id
          if (this.model.actType === 20) {
            param['discount'] = parseFloat(this.autoModel.autoValue) * 10
          } else if (this.model.actType === 22) {
            param['special'] = parseFloat(this.autoModel.autoValue) * 100
          } else if (this.model.actType === 21) {
            param['reduce'] = parseFloat(this.autoModel.autoValue) * 100
          }
          let priceTailBegin = that.autoModel.priceTailBegin
          let priceTailEnd = that.autoModel.priceTailEnd
          if (this.autoModel.priceType === 'tail') {
            param['ruleType'] = 1

            if (priceTailBegin) {
              param['priceTailBegin'] = parseFloat(priceTailBegin) * 100
            }
            if (priceTailEnd) {
              param['priceTailEnd'] = parseFloat(priceTailEnd) * 100
            }
          } else {
            param['ruleType'] = 2
            param['priceTailBegin'] = 0
            param['priceTailEnd'] = 0
          }

          postAction(this.url.posMarketActAuto, param)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.autoConfirmLoading = false
              that.autoClose()
            })
        } else {
          return false
        }
      })
    },
    batchRow() {
      // console.log(this.selectionRows)
      // if (this.selectionRows.length === 0) {
      //   this.$message.warning('请选择商品')
      //   return false
      // }

      this.batchVisible = true
      this.handleActType()
    },
    autoRule() {
      getAction(this.url.queryByActId, { actId: this.model.id }).then((res) => {
        if (res.success) {
          this.autoModel = res.result
          console.log('autoModel:', this.autoModel)
          if (this.autoModel.ruleType === 1) {
            this.$set(this.autoModel, 'priceType', 'tail')
            let priceTailBegin = this.autoModel.priceTailBegin
            let priceTailEnd = this.autoModel.priceTailEnd
            if (priceTailBegin) {
              this.$set(this.autoModel, 'priceTailBegin', priceTailBegin / 100)
            }
            if (priceTailEnd) {
              this.$set(this.autoModel, 'priceTailEnd', priceTailEnd / 100)
            }
          } else {
            this.$set(this.autoModel, 'priceType', 'price')
          }
          if (this.model.actType === 20) {
            this.$set(this.autoModel, 'autoValue', parseFloat(this.autoModel.discount) / 10)
          } else if (this.model.actType === 22) {
            this.$set(this.autoModel, 'autoValue', parseFloat(this.autoModel.special) / 100)
          } else if (this.model.actType === 21) {
            this.$set(this.autoModel, 'autoValue', parseFloat(this.autoModel.reduce) / 100)
          }
          this.autoModel.bizStatus = this.autoModel.bizStatus + ''
        } else {
          this.autoModel = {}
        }

        if (this.model.actType === 20) {
          this.autoLabel = '折扣(1-10之间)'
          this.autoModel.ruleType = 1
        } else if (this.model.actType === 22) {
          this.autoLabel = '特价'
          this.autoModel.ruleType = 2
        } else if (this.model.actType === 21) {
          this.autoLabel = '立减'
          this.autoModel.ruleType = 1
        }
        let priceTailBegin = this.autoModel.priceTailBegin
        let priceTailEnd = this.autoModel.priceTailEnd
        if (priceTailBegin === 0 && priceTailEnd === 0) {
          this.$set(this.autoModel, 'priceTailBegin', null)
          this.$set(this.autoModel, 'priceTailEnd', null)
        }

        this.autoVisible = true
      })
    },
    getQueryParams() {
      //获取查询条件
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize

      return filterObj(param)
    },
    getQueryField() {
      //TODO 字段权限控制
      var str = 'id,'
      this.columns.forEach(function (value) {
        str += ',' + value.dataIndex
      })
      return str
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      //分页勾选缓存前面勾选的记录
      this.selectedRowKeys = selectedRowKeys
      if (selectionRows.length == 0) {
        let newSelectionRows = this.selectionRows.filter((x) => this.selectedRowKeys.includes(x.id))
        this.selectionRows = newSelectionRows
      } else {
        selectionRows.forEach((x) => {
          this.selectionRows.push(x)
        })
      }
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    loadData(arg) {
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams() //查询条件
      this.loading = true
      postAction(this.url.listItemUrl, params)
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result.records || res.result
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    selectOk(selectionRows) {
      console.log('selectionRows', selectionRows)
      this.loadData(1)
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      console.log(pagination)
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    },
    loadDepartTree() {
      queryDepartTreeList1().then((res) => {
        if (res.success) {
          let departList = res.result
          if (departList.length == 1 && departList[0].orgType == 1) {
            departList = departList[0].children
          }
          this.departModel.departTreeOptions = departList

          this.departModel.departTreeOptions.forEach((x) => {
            if (!x['children']) {
              x['children'] = []
            }
            let allShop = { title: '全部门店', value: '0' }
            x['children'].unshift(allShop)
          })
        }
      })
    },
    onDepartChange(value, selectedOptions) {
      console.log('value:', value)
      console.log('selectedOptions:', selectedOptions)
      this.orgIds = value && value.length > 0 ? value[0] : ''
      this.shopIds = value && value.length > 0 ? value[1] : ''
    },
    handleDateChange1(date, dateString) {
      this.model.startTime = dateString[0]
      this.model.endTime = dateString[1]
    },
    init() {
      this.isEdit = true
      this.model.bizStatus = 0
    },
    add() {
      //初始化默认值
      this.edit({})
    },
    edit(record) {
      this.model = Object.assign({}, record)
      this.visible = true
      this.loadDepartTree()
      this.isEdit = true
      this.dataSource = []
      this.model.bizStatus = 0
      this.actId = '0'
      this.isDiscount = false
      if (this.model.id) {
        console.log('edit, this.model = ', this.model)
        this.isDiscount = this.model.actType === 20
        this.isEdit = false
        this.actId = this.model.id
        this.$set(this.model, 'dateRange', [moment(this.model.startTime), moment(this.model.endTime)])
        this.$set(this.queryParam, 'params', { actId: this.model.id })
        this.scopeShops = this.model.scopeShopIds.split('_')
        this.$set(this.model, 'selecteddeparts', [this.scopeShops[0], this.scopeShops[1]])
        this.orgIds = this.scopeShops[0]
        this.shopIds = this.scopeShops[1]
        this.handleActType()
        this.handleLimit()

        this.loadData(1)
      }
      this.model.saveModal = 'MAIN'
    },
    handleLimit() {
      let notGivePoints = this.model.notGivePoints
      let notUsePoints = this.model.notUsePoints
      let notUseCoupon = this.model.notUseCoupon

      let useLimitRule = []
      if (notGivePoints === 1) {
        useLimitRule.push('not_give_points')
      }
      if (notUsePoints === 1) {
        useLimitRule.push('not_use_points')
      }
      if (notUseCoupon === 1) {
        useLimitRule.push('not_use_coupon')
      }
      this.$set(this.model, 'useLimitRule', useLimitRule)
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.$refs.form.clearValidate()
    },
    buildParam() {
      if(this.model.selecteddeparts[1] != 0){
        this.userScope = 'PART'
        this.orgType = 3
      }

      let param = {
        actNm: this.model.actNm,
        startTime: this.model.startTime,
        actType: this.model.actType,
        id: this.model.id,
        endTime: this.model.endTime,
        useDesc: this.model.useDesc,
        digit: this.model.digit,
        saveModal: this.model.saveModal,
        actShops: [
          {
            orgId: this.model.selecteddeparts[0],
            orgType: this.orgType,
            shopId: this.model.selecteddeparts[1],
            useScope: this.userScope,
          },
        ],
      }

      // 活动限制
      let actUseLimit = {
        actId: this.model.id,
        memberScope: this.model.memberScope,
        notGivePoints: 0,
        notUsePoints: 0,
        notUseCoupon: 0,
      }
      let useLimitRule = this.model.useLimitRule
      console.log('===useLimitRule===', useLimitRule)
      if (!useLimitRule || useLimitRule.length === 0) {
        actUseLimit.notGivePoints = 0
        actUseLimit.notUsePoints = 0
        actUseLimit.notUseCoupon = 0
      } else {
        for (let i of useLimitRule) {
          if (i === 'not_give_points') {
            actUseLimit.notGivePoints = 1
          }
          if (i === 'not_use_points') {
            actUseLimit.notUsePoints = 1
          }
          if (i === 'not_use_coupon') {
            actUseLimit.notUseCoupon = 1
          }
        }
      }
      console.log('===actUseLimit===', actUseLimit)

      param['actUseLimit'] = actUseLimit

      return filterObj(param)
    },
    handleOk() {
      if (this.isDiscount) {
        let digit = this.model.digit
        if (!digit) {
          this.$message.warning('请填写结算金额小数位')
          return false
        }
      }
      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          if (!this.model.id) {
            httpurl += this.url.add
          } else {
            httpurl += this.url.edit
          }

          let param = that.buildParam()
          postAction(httpurl, param)
            .then((res) => {
              if (res.success) {
                that.actId = res.result
                that.model.id = res.result
                that.isEdit = false
                this.$set(this.queryParam, 'params', { actId: this.model.id })
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
              // that.close()
            })
        } else {
          return false
        }
      })
    },
    handleCancel() {
      this.close()
    },
    newRow() {
      this.$refs.selectSpuForm.search(this.orgIds, this.model)
      this.$refs.selectSpuForm.title = '选择商品'
      this.$refs.selectSpuForm.visible = true
    },
    removeRow(id) {
      deleteAction(this.url.delItemUrl, { id: id })
        .then((res) => {
          if (res.success) {
            this.$message.info(res.message)
            this.loadData(1)
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {})
    },
    clearProd() {
      let that = this
      Modal.confirm({
        title: '确定清空商品?',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          console.log('OK')
          that.deleteItemAll()
        },
        onCancel() {
          console.log('Cancel')
        },
      })
    },
    deleteItemAll() {
      console.log('method=deleteItemAll')
      deleteAction(this.url.deleteAllItemUrl, { actId: this.actId })
        .then((res) => {
          if (res.success) {
            this.$message.info(res.message)
            this.loadData(1)
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {})
    },
    handlerRowChange(id, markPrice, value, column) {
      console.log('value=', value, ',id=', id)
      let newData = [...this.itemListData]
      let target = newData.filter((item) => id === item.id)[0]
      if (target) {
        target['markPrice'] = markPrice
        target[column] = value
      } else {
        target = {}
        target['markPrice'] = markPrice
        target['id'] = id
        target[column] = value
        newData.push(target)
      }
      this.itemListData = newData
    },
  },
}
</script>
<style scoped>
.editable-cell-icon,
.editable-cell-icon-check {
  margin-left: 10px;
  cursor: pointer;
}
.editable-cell-icon:hover,
.editable-cell-icon-check:hover {
  color: #108ee9;
}

.limitCheck{
  display: inline-block;
  padding: 0 10px;
  border-radius: 10px;
  border: 1px solid #d9d9d9;
}
</style>